import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'image_util.dart';

/// 图片加载（支持本地与网络图片）
class ImageLoad extends StatelessWidget {
  
  const ImageLoad(this.url, {
    Key key,
    this.width, 
    this.height,
    this.fit,
    this.format: 'png',
    this.holderImg: 'none',
    this.holderPackage,
    this.errorImg: 'none',
    this.errorPackage,
    this.package,
  }): super(key: key);
  
  final String url;
  final double width;
  final double height;
  final BoxFit fit;
  final String format;
  final String holderImg;
  final String holderPackage;
  final String errorImg;
  final String errorPackage;
  final String package;
  
  @override
  Widget build(BuildContext context) {
    if (url == null || url.isEmpty || url == 'null') {
     return _LoadAssetImage(holderImg,
       height: height,
       width: width,
       fit: fit,
       format: format
     );
      // return Container(color: Colors.grey,);
    } else {
      if (url.startsWith('http') || url.startsWith('https')) {
        return CachedNetworkImage(
          imageUrl: url,
          placeholder: (context, url) => _LoadAssetImage(holderImg, height: height, width: width, fit: fit, package: holderPackage,),
          errorWidget: (context, url, error) => _LoadAssetImage(errorImg, height: height, width: width, fit: fit, package: errorPackage,),
          width: width,
          height: height,
          fit: fit,
        );
      } else {
         return _LoadAssetImage(url,
             height: height,
             width: width,
             fit: fit,
             format: format,
             package: package,
         );
      }
    }
  }
}

/// 加载本地资源图片
class _LoadAssetImage extends StatelessWidget {
  
  const _LoadAssetImage(this.url, {
    Key key,
    this.width,
    this.height, 
    this.cacheWidth,
    this.cacheHeight,
    this.fit,
    this.format: 'png',
    this.color,
    this.package
  }): super(key: key);

  final String url;
  final double width;
  final double height;
  final int cacheWidth;
  final int cacheHeight;
  final BoxFit fit;
  final String format;
  final Color color;
  final String package;
  
  @override
  Widget build(BuildContext context) {

    return Image.asset(
      getImgPath(url, format: format),
      height: height,
      width: width,
      cacheWidth: cacheWidth,
      cacheHeight: cacheHeight,
      fit: fit,
      color: color,
      package: package,
      /// 忽略图片语义
      excludeFromSemantics: true,
    );
  }
}
